<template>
  <section class="conversation-list">
    <ScrollView style="height: 100%">
      <virtual-list
        :data-component="conversationItemView"
        :data-sources="conversationInfoList"
        :data-key="conversationInfoKey"
        ref="virtualList"
        :onScroll="onScroll"
        :estimate-size="30"
      />
    </ScrollView>

    <vue-context
      ref="menu"
      class="right-click"
      v-slot="{ data: conversationInfo }"
      v-on:close="onConversationItemContextMenuClose"
    >
      <!-- 置顶 -->
      <li
        class="menu-item hover click"
        @click.prevent="setConversationTop(conversationInfo)"
      >
        <template v-if="conversationInfo?.top">
          <img src="@/kang/img/icon_cancel_sticky.png" />
          <span>{{ $t('conversation.cancel_sticky_top') }}</span>
        </template>

        <template v-else>
          <img src="@/kang/img/icon_sticky.png" />
          <span>{{ $t('conversation.sticky_top') }}</span>
        </template>
      </li>

      <!-- 消息免打扰 -->
      <li
        class="menu-item hover click"
        @click.prevent="setConversationSilent(conversationInfo)"
      >
        <template v-if="conversationInfo?.isSilent">
          <img src="@/kang/img/icon_enable_notify.png" />
          <span>{{ $t('conversation.enable_notification') }}</span>
        </template>

        <template v-else>
          <img src="@/kang/img/icon_disable_notify.png" />
          <span>{{ $t('conversation.disable_notification') }}</span>
        </template>
      </li>

      <!-- 在独立窗口打开 -->
      <li
        class="menu-item hover click"
        @click.prevent="
          showConversationFloatPage(conversationInfo.conversation)
        "
        v-if="sharedMiscState.isElectron"
      >
        <img src="@/kang/img/icon_open_window.png" />
        <span>{{ $t('conversation.show_in_float_window') }}</span>
      </li>

      <!-- 消息设置为未读 -->
      <li
        class="menu-item hover click"
        v-show="
          conversationInfo &&
          (!sharedConversationState.currentConversationInfo ||
            !sharedConversationState.currentConversationInfo.conversation.equal(
              conversationInfo.conversation
            )) &&
          conversationInfo._unread === 0
        "
        @click.prevent="markConversationAsUnread(conversationInfo.conversation)"
      >
        <img src="@/kang/img/icon_unread.png" />
        <span>{{ $t('conversation.mark_as_unread') }}</span>
      </li>

      <!-- 消息设置为已读 -->
      <li
        class="menu-item hover click"
        v-show="
          conversationInfo &&
          (!sharedConversationState.currentConversationInfo ||
            !sharedConversationState.currentConversationInfo.conversation.equal(
              conversationInfo.conversation
            )) &&
          conversationInfo._unread > 0
        "
        @click.prevent="
          clearConversationUnreadStatus(conversationInfo.conversation)
        "
      >
        <img src="@/kang/img/icon_read.png" />
        <span>{{ $t('conversation.mark_as_read') }}</span>
      </li>

      <!-- 删除消息 -->
      <li
        class="menu-item hover click"
        @click.prevent="removeConversation(conversationInfo)"
      >
        <img src="@/kang/img/icon_delete.png" />
        <span class="cl-error">{{ $t('common.delete') }}</span>
      </li>
    </vue-context>
  </section>
</template>

<script>
import ConversationItemView from './ConversationItemView.vue'
import store from '../../../store'
import wfc from '../../../wfc/client/wfc'
import IpcEventType from '../../../ipcEventType'
import { ipcRenderer } from '../../../platform'
import { markRaw } from 'vue'
import mitt from '@/kang/js/mitt'
import api from '@/kang/js/api'

export default {
  name: 'ConversationListView',
  data() {
    return {
      sharedConversationState: store.state.conversation,
      sharedMiscState: store.state.misc,
      conversationItemView: markRaw(ConversationItemView),
      currentConversationIndex: 0,
      firstCollectData: {}, // 第一条收藏的消息
    }
  },

  created() {
    this.$eventBus.$on(
      'showConversationContextMenu',
      ([event, conversationInfo]) => {
        this.showConversationItemContextMenu(event, conversationInfo)
      }
    )
    this.$eventBus.$on(
      'scrollToNextUnreadConversation',
      this.scrollToNextUnreadConversation
    )
    mitt.on('updateFirstCollectData', this.updateFirstCollectData)
    this.updateFirstCollectData()
  },

  unmounted() {
    this.$eventBus.$off('showConversationContextMenu')
    this.$eventBus.$off('scrollToNextUnreadConversation')
    mitt.off('updateFirstCollectData', this.updateFirstCollectData)
  },

  methods: {
    async updateFirstCollectData() {
      const params = {
        count: 1,
      }

      const { code, data } = await api.getCollectList(params)

      if (code === 200) {
        if (data?.items?.length) {
          this.firstCollectData = data.items[0]
        } else {
          this.firstCollectData = {}
        }
      }
    },
    setConversationTop(conversationInfo) {
      store.setConversationTop(
        conversationInfo.conversation,
        conversationInfo.top > 0 ? 0 : 1
      )
    },

    setConversationSilent(conversationInfo) {
      store.setConversationSilent(
        conversationInfo?.conversation,
        !conversationInfo?.isSilent
      )
    },

    removeConversation(conversationInfo) {
      store.removeConversation(conversationInfo.conversation)
    },

    conversationInfoKey(conversationInfo) {
      let conv = conversationInfo.conversation
      return conv.target + '-' + conv.type + '-' + conv.line
    },
    scrollActiveElementCenter() {
      let el = this.$el.getElementsByClassName('active')[0]
      el && el.scrollIntoView({ behavior: 'instant', block: 'center' })
    },

    showConversationItemContextMenu(event, conversationInfo) {
      if (!this.$refs.menu) {
        return
      }
      this.sharedConversationState.contextMenuConversationInfo =
        conversationInfo
      this.$refs.menu.open(event, conversationInfo)
    },

    onConversationItemContextMenuClose() {
      this.sharedConversationState.contextMenuConversationInfo = null
    },

    clearConversationUnreadStatus(conversation) {
      wfc.clearConversationUnreadStatus(conversation)
    },

    markConversationAsUnread(conversation) {
      wfc.markConversationAsUnread(conversation, true)
    },

    showConversationFloatPage(conversation) {
      let hash = window.location.hash
      let url = window.location.origin
      if (hash) {
        url = window.location.href.replace(hash, '#/conversation-window')
      } else {
        url += '/conversation-window'
      }
      ipcRenderer.send(IpcEventType.showConversationFloatPage, {
        url: url,
        type: conversation.type,
        target: conversation.target,
        line: conversation.line,
      })

      store.addFloatingConversation(conversation)
      if (
        this.sharedConversationState.currentConversationInfo &&
        this.sharedConversationState.currentConversationInfo.conversation.equal(
          conversation
        )
      ) {
        store.setCurrentConversation(null)
      }
    },

    onScroll(e, params) {
      if (params) {
        this.currentConversationIndex = params.end
      }
    },

    // 滑动到下一个未读会话
    scrollToNextUnreadConversation() {
      let currentConversationIndex = this.currentConversationIndex
      let nextUnreadConversationIndex = this.conversationInfoList.findIndex(
        (ci, index) => {
          if (index <= currentConversationIndex) {
            return false
          }
          return !ci.isSilent && ci._unread > 0
        }
      )

      if (nextUnreadConversationIndex === -1 && currentConversationIndex > -1) {
        nextUnreadConversationIndex = this.conversationInfoList.findIndex(
          (ci, index) => {
            return !ci.isSilent && ci._unread > 0
          }
        )
      }

      console.log(
        'scrollToNextUnreadConversation',
        this.currentConversationIndex,
        nextUnreadConversationIndex,
        this.$refs['virtualList'].getOffset()
      )
      if (nextUnreadConversationIndex > -1) {
        this.$refs['virtualList'].scrollToIndex(nextUnreadConversationIndex)
      }
    },
  },
  activated() {
    this.scrollActiveElementCenter()
  },
  computed: {
    conversationInfoList() {
      console.log(
        this.sharedConversationState.conversationInfoList,
        this.sharedConversationState.floatingConversations,
        'update'
      )
      return [
        { type: 'collect', conversation: { ...this.firstCollectData } },
        ...this.sharedConversationState.conversationInfoList.filter((ci) => {
          const index =
            this.sharedConversationState.floatingConversations.findIndex((c) =>
              c.equal(ci.conversation)
            )
          return index === -1
        }),
      ]
    },
  },

  components: { ConversationItemView },
}
</script>

<style lang="scss" scoped>
.conversation-list {
  height: 100%;
  overflow: auto;
}
</style>
